package com.dc.common.aop;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.dc.base.exception.BusinessException;
import com.dc.common.constants.ConstantsCommon;
import com.dc.common.model.BaseModel;

/**
 * 验证表单重复提交切面
 * @author Shen
 * @date 2018年4月10日 下午1:26:59
 */
@Component
@Aspect
public class ResubmitOperationAspect {

	@Pointcut("@annotation(com.dc.common.aop.ResubmitAop)")
	public void controllerAspect() {
	}

	@Before("controllerAspect() && @annotation(data)")
	public void doBefore(JoinPoint point, ResubmitAop data) throws Exception {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpSession session = request.getSession();
		// 判断session和请求传过来的token令牌是否一致
		// 获取session中的token
		String token_fromSession = (String) session.getAttribute(ConstantsCommon.TOKEN);

		// 获取baseModel
		BaseModel baseModel = new BaseModel();
		if (point.getArgs() != null) {
			for (Object obj : point.getArgs()) {
				if (obj.getClass() == BaseModel.class) {
					baseModel = (BaseModel) obj;
					break;
				}
			}
		}

		// 获取请求参数中的token
		String token_fromBaseModel = baseModel.getToken();
		
		// 比较token
		// token一致的情况下清除session中的token,token不一致的情况下返回错误信息
		if (token_fromSession != null && token_fromBaseModel != null && !"".equals(token_fromSession)
				&& !"".equals(token_fromBaseModel) && token_fromSession.equals(token_fromBaseModel)) {
			session.setAttribute(ConstantsCommon.TOKEN, null);
		}else{
			throw new BusinessException(7,"请不要重复提交！");
		}
		
		
	}

}
